<template>
  <view class="navigation">
    <eui-navbar ref="EuiNavBar" title="任务设置" displayable="true" color="#000000" backgroundColor="#FFFFFF" rightIcon=""/>
    <view class="main-view" :style="{ height: scrollHeight + 'rpx' }">
      <scroll-view scroll-y="true" style="height: 100%;">
        <eui-card title="群组设置" topMargin="0">
          <template v-slot:extra>
            <view class="extra-view" @click="addGroup">
              <text class="extra-text" :class="[theme]">添加群组</text>
            </view>
          </template>
          <view v-if="groupList.length > 0" class="item-view" v-for="(item, index) in groupList" :key="index" @click="itemGroupClick(item)">
            <view class="content-view">
              <text class="title">{{ item.Name }}</text>
              <text class="detail" v-if="item.OnDutyName">{{ item.OnDutyName }}</text>
            </view>
            <view class="right-view">
              <text style="margin-right: 10rpx">添加成员</text>
              <eui-uicons type="right" size="24" color="#888888" />
            </view>
          </view>
          <view v-else>
            <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min" />
            <view class="no-data-text">暂无任何群组</view>
          </view>
        </eui-card>
        <eui-card title="任务设置">
          <template v-slot:extra>
            <view class="extra-view" @click="addTask">
              <text class="extra-text" :class="[theme]">添加任务</text>
            </view>
          </template>
          <view v-if="taskList.length > 0" class="item-view" v-for="(item, index) in taskList" :key="index" @click="itemTaskClick(item, index)">
            <view class="content-view">
              <text class="title">{{ item.c_name }}</text>
              <text class="detail">{{ item.c_role_name }}</text>
            </view>
            <view class="right-view">
              <text style="margin-right: 10rpx">修改</text>
              <eui-uicons type="right" size="24" color="#888888" />
            </view>
          </view>
          <view v-else>
            <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min" />
            <view class="no-data-text">暂无任何任务</view>
          </view>
        </eui-card>
      </scroll-view>
    </view>
    <eui-popup ref="popupGroup" background-color="#f8f8f8" type="center" :mask-click="false" :animation="false">
      <view class="popup-group">
        <TaskGround :formatData="formatGroupData" @hidePopup="hideGroupPopup"
                    @clickFunc="confirmGroupPopup" @chooseStore="chooseStore"
                    :dutyRangeList="dutyRangeList"/>
      </view>
    </eui-popup>
  </view>
</template>

<script setup type="ts">
import { storeToRefs } from 'pinia';
import {computed, onMounted, ref} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import {getRdsSysConfig, init} from "@/hooks/init";
import { getRelatedName, getDictName, getUserDictSelectList, getDictSelect, getDictSelectList, getWeightUnits, getDictList } from '../../components/RelatedName.js';
import Enjoy from "@/common/enjoy";
import { getRdsUrl, rdsRequest } from "@/hooks/rdsServices";
import {useMainStore} from "@/store/modules/store";
import {useLoginStore} from "@/store/modules/useLoginStore";
import TaskGround from '../components/taskGroup.vue'
import Guid from '@/common/guid';
import service from "@/common/service";
import useService from '@/hooks/useService';
import useUpload from "@/hooks/useUpload";
import { useThemeStore } from '@/store/themeStore';
const themeStore = useThemeStore(); // 主题
const { theme } = storeToRefs(themeStore);

const mainService = useService({ prefix: "mainApi" });
const { upload, remove, fetchFile } = useUpload({ prefix: 'mainApi' });
const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const LoginStore = useLoginStore();

const scrollHeight = ref(0);
// 群组设置
const groupList = ref([]);
const popupGroup = ref(null);
const dutyRangeList = ref([]); // 在岗配置
const formatGroupData = ref({
  groupName: '', // 群组名称
  dutyConfig: '', // 在岗配置
  groupStore: '', // 所属机构
})
// 任务设置
const taskList = ref([]);


// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) {
      let info = uni.createSelectorQuery().select(".main-view");
      info.boundingClientRect(function (data) {
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        scrollHeight.value = height / (res.windowWidth / 750) - 20;
      }).exec()
    }
  });
};

// 获取字典
const getSysConfig = async () => {
  dutyRangeList.value = getDictSelectList('在岗配置');
}

onMounted((e) => {
  getListHeight()
});

onLoad(async (e) => {
  service.enjoyShowLoading('正在加载...');
  await getSysConfig();
  await getGroupList();
  await getTaskTypeList();
  service.enjoyHideLoading();
})

// 获取群组列表
const getGroupList = async () => {
  const result = await rdsRequest(rdsUrl.mainApi, 'taskdefine', 'FetchTaskRoles', '');
  if (result && result.length > 0) {
    groupList.value = result;
  } else {
    groupList.value = [];
  }
}

// 获取任务类型列表
const getTaskTypeList = async () => {
  const req = {
    IsNotPage: true,
    CurrentPage: 1,
    PageSize: 100,
    WhereList: []
  }
  const result = await rdsRequest(rdsUrl.mainApi, 'taskdefine', 'EnjoyQueryList', req);
  if (result && result.ReturnObject) {
    taskList.value = result.ReturnObject;
  } else {
    taskList.value = [];
  }
}

// 添加群组
const addGroup = () => {
  popupGroup.value.open();
}

// 关闭弹框
const hideGroupPopup = () => {
  formatGroupData.value = {
    groupName: '', // 群组名称
    dutyConfig: '', // 在岗配置
    groupStore: '', // 所属机构
  }
  popupGroup.value.close();
}

// 确认添加群组
const confirmGroupPopup = async () => {
  let { groupName, dutyConfig, groupStore } = formatGroupData.value
  if (!groupName) {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '名称不能为空！'
    });
    return
  }
  service.enjoyShowLoading('添加中...');
  let req = {
    AccountType: '',
    ClassName: '任务管理角色',
    IsRoleClass: false,
    ItemKey:"[object Object]-new",
    Items:[],
    Name: groupName,
    OnDuty: dutyConfig,
    RoleClassCode: '4',
  }
  if (groupStore) {
    req.StoreId = groupStore;
  }
  const result = await rdsRequest(rdsUrl.mainApi, 'h5Role', 'SaveRoleItem', req);
  hideGroupPopup();
  await getGroupList();
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: '添加成功'
  });
  service.enjoyHideLoading();
}

// 选择机构
const chooseStore = () => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  parms.SelectionType = "机构选择";
  parms.SelectedItems = formatGroupData.value.groupStore;
  Enjoy.OpenDialog(parms)
}

const SelectionChanged = async (e) => {
  formatGroupData.value.groupStore = e.BackParms.Key;
}

// 添加群组成员
const itemGroupClick = (item) => {
  uni.navigateTo({
    url: `./groupMember?code=${item.Code}&classCode=${item.RoleClassCode}`,
  });
}

// 添加任务类型
const addTask = () => {
  uni.navigateTo({
    url: './taskSetting',
  });
}

// 修改任务类型
const itemTaskClick = (item, index) => {
  uni.navigateTo({
    url: `./taskSetting?taskId=${item.c_guid}&taskName=${item.c_name}`,
  });
}

// 刷新群组
const updateGroupList = async () => {
  console.log('======刷新群组: ');
  service.enjoyShowLoading('正在加载...');
  await getGroupList();
  service.enjoyHideLoading();
}

// 刷新任务类型
const updateTaskList = async () => {
  console.log('======刷新任务类型: ');
  service.enjoyShowLoading('正在加载...');
  await getTaskTypeList();
  service.enjoyHideLoading();
}

defineExpose({
  updateGroupList,
  updateTaskList,
})

</script>

<style lang="scss" scoped>
@import '@/main.scss';

.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}

.main-view {
  width: 100%;
  margin-top: 20rpx;
  display: flex;
  position: relative;
}

.extra-text {
  font-family: $uni-font-family;
  font-weight: $uni-font-weight-level1;
  font-size: $uni-font-size-level5;
  color: var(--theme-color);
  line-height: 33rpx;
  text-align: center;
  font-style: normal;
}

.item-view {
  width: 100%;
  height: 113rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  border-bottom: 1rpx solid $uni-line-color;
}

.content-view {
  display: flex;
  flex-direction: column;
  flex: 1;
  font-family: $uni-font-family;
  font-style: normal;
  justify-content: center;
  align-items: flex-start;

  .title {
    font-weight: $uni-font-weight-level3;
    font-size: $uni-font-size-level3;
    color: $uni-text-color-primary;
    line-height: 40rpx;
  }
  .detail {
    font-weight: $uni-font-weight-level2;
    font-size: $uni-font-size-level5;
    color: $uni-text-color-hint;
    line-height: 33rpx;
  }
}

.right-view {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  font-family: $uni-font-family;
  font-weight: $uni-font-weight-level1;
  font-size: $uni-font-size-level7;
  color: $uni-text-color-hint;
  line-height: 28rpx;
  font-style: normal;
}

// 添加群组弹框
.popup-group {
  width: 630rpx;
  height: 520rpx;
}

.image-min {
  width: 100%;
  height: 150rpx;
  opacity: 0.6;
  margin-top: -40rpx;
}

.no-data-text {
  text-align: center;
  color: #cccccc;
  font-size: 24rpx;
  margin-top: -10rpx;
  margin-bottom: 20rpx;
}

</style>
